package com.showcase.cloud.gateway.config;


import com.netflix.loadbalancer.IPing;
import com.netflix.loadbalancer.Server;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

@Slf4j
public class HealthExamination implements IPing {

    private RestTemplate restTemplate;

    public HealthExamination(RestTemplate restTemplate){
        this.restTemplate = restTemplate;
    }

    @Override
    public boolean isAlive(Server server)
    {
        String urlStr = "http://";
//        if (isSecure){
//            urlStr = "https://";
//        }else{
//            urlStr = "http://";
//        }
        urlStr += server.getId()+"/demo/health";
//        if(config.getProperties().get("pingAppendString") != null){
//            urlStr += config.getProperties().get("pingAppendString");
//        }
        try{
            ResponseEntity<String> heath = restTemplate.getForEntity(urlStr, String.class);
            if (heath.getStatusCode() == HttpStatus.OK)
            {
                log.info("ping " + urlStr + " success and response is " + heath.getBody());
                return true;
            }
            log.info("ping " + urlStr + " error and response is " + heath.getBody());
            return false;
        }
        catch (Exception e){
            log.warn("ping " + urlStr + " failed");
            return false;
        }
    }
}
